'''
Created on Jan 18, 2015

@author: dewey
'''

METADATA_SERIES_OPTIONS = "plot_series_options_%s" #appended by proxy id

MULTIPLOT_ROWS = "rows"
MULTIPLOT_COLS = "cols"
MULTIPLOT_FIGSIZE = "figsize"
MULTIPLOT_SYNCHRONIZE_Y_AXIS = "synchronize_y_axis"
MULTIPLOT_Y_AXIS_RANGE = "y_axis_range"


PLOT_RANGE_X_AXIS = "range_value" #2-tuple of min/max values
PLOT_RANGE_Y_AXIS = "depth_range" #2-tuple of min/max values
PLOT_TITLE = "title" #string title or None/omitted
PLOT_VALUE_LABEL = "value_label" #value(on x axis) label
PLOT_Y_AXIS_LABEL = "y_axis_label" #y axis label
PLOT_X_AXIS_TICKS_COUNT = "value_ticks_count" #value (x axis) tick count
PLOT_Y_AXIS_TICKS_COUNT = "y_axis_ticks_count" #y axis tick count
PLOT_SERIES_XY_LIST = "xy_series_list" #a list of 2 dimensional arrays (x, y, [x error, [y error]]) to be displayed as series
PLOT_SERIES_OPTIONS_LIST = "xy_series_options_list" #a list of the same length as the number of series containing series options
PLOT_Y_AXIS_REVERSED = "y_axis_reversed" #should the y axis be reversed (default=True)
PLOT_SHOW_X_AXIS_LABELS = "show_x_axis_labels"
PLOT_SHOW_Y_AXIS_LABELS = "show_y_axis_labels"
PLOT_X_AXIS_VISIBLE = "x_axis_visible"
PLOT_Y_AXIS_VISIBLE = "y_axis_visible"
PLOT_BORDER_VISIBLE = "border_visible"
PLOT_BACKGROUND = "background"


SERIES_ERROR_BARS = "error_bars" #the only option that is not an option for Line2D
SERIES_MARKER = "marker" # see http://matplotlib.org/api/markers_api.html#module-matplotlib.markers
                        # options are: . , o v ^ < > 1 2 3 4 8 s p * h H + x D d | 
SERIES_MARKER_SIZE = "markersize"
SERIES_COLOR = "color"
SERIES_LINE_WIDTH = "linewidth"
SERIES_LINE_STYLE = "linestyle" #['-' | '--' | '-.' | ':' | 'None' | ' ' | '']
SERIES_LABEL = "label"

DEFAULT_MULTIPLOT_OPTIONS = {}
DEFAULT_MULTIPLOT_OPTIONS[MULTIPLOT_ROWS] = 1
DEFAULT_MULTIPLOT_OPTIONS[MULTIPLOT_SYNCHRONIZE_Y_AXIS] = True

DEFAULT_PLOT_OPTIONS = {}
DEFAULT_PLOT_OPTIONS[PLOT_X_AXIS_TICKS_COUNT] = 4
DEFAULT_PLOT_OPTIONS[PLOT_Y_AXIS_REVERSED] = True
DEFAULT_PLOT_OPTIONS[PLOT_BACKGROUND] = False

DEFAULT_SERIES_OPTIONS = {}
DEFAULT_SERIES_OPTIONS[SERIES_ERROR_BARS] = True
DEFAULT_SERIES_OPTIONS[SERIES_COLOR] = "black"
DEFAULT_SERIES_OPTIONS[SERIES_MARKER_SIZE] = 4

DENDROGRAM_TOTAL_DISSIMILARITY = "total_dissimilarity"
DENDROGRAM_INCREASE_DISSIMILARITY = "increase_dissimilarity"
DENDROGRAM_EQUAL_INTERVAL = "equal_interval"

import pystrat.units as units

from pystrat.datamodel import VerticalData, Dendrogram
from pystrat.project import METADATA_LOCATION_ID

from matplotlib.figure import Figure
from matplotlib.backends.backend_pdf import PdfPages

GROUP_BY_LOCATION = "groupby_location"
GROUP_BY_VDATA = "groupby_proxy"
YAXIS_DEPTH = "depth"
YAXIS_DEPTH_REVERSED = "depth_reversed"
YAXIS_AGE = "age"
YAXIS_AGE_REVERSED = "age_inversed"

def _loc_id(vdata):
    return vdata.metadata(METADATA_LOCATION_ID)

def generate_plot_options(list_of_vdata, project=None, group_by=None, error_function=None, yaxis=YAXIS_DEPTH, default_series=None):
    opts_out = []
    unique_locations = set()
    unique_vdata_ids = set()
    first_vdata = None
    vdata_items = []
    dendrogram_items = []
    for vdata in list_of_vdata:
        if isinstance(vdata, VerticalData):
            unique_vdata_ids.add(vdata._id)
            unique_locations.add(_loc_id(vdata))
            vdata_items.append(vdata)
        elif isinstance(vdata, Dendrogram):
            dendrogram_items.append(vdata)
    multiple_locations = len(unique_locations) > 1
    
    yaxis_age = (yaxis == YAXIS_AGE) or (yaxis == YAXIS_AGE_REVERSED)
    yaxis_reversed = (yaxis == YAXIS_DEPTH_REVERSED) or (yaxis == YAXIS_AGE_REVERSED)
    
    if group_by is None:
        if default_series is None:
            default_series = {}
            default_series[SERIES_LINE_STYLE] = "-"
        series_style = __multiple_series_options(default_series, 1)[0]
        for vdata in vdata_items:
            opts = {}
            name = vdata.name()
            if multiple_locations and project:
                name = "%s: %s" % (project.locations[_loc_id(vdata)].name(), name)
            opts[PLOT_TITLE] = name
            opts[PLOT_SERIES_XY_LIST] = [proxy_xy_values(vdata, project, error_function, yaxis_age),]
            opts[PLOT_SERIES_OPTIONS_LIST] = [series_style,]
            opts[PLOT_Y_AXIS_REVERSED] = yaxis_reversed
            opts_out.append(opts)
    elif group_by == GROUP_BY_VDATA:
        grouped_list = []
        listcopy = list(vdata_items)
        base_index = 0
        while True:
            if base_index > len(listcopy)-1:
                break
            base_vdata = listcopy[base_index]
            current_list = []
            current_list.append(base_vdata)
            if base_index == len(listcopy)-1:
                grouped_list.append(current_list)
                break
            indicies_added = []
            for index in reversed(range(base_index+1, len(listcopy))):
                vdta_to_add = listcopy[index]
                if vdta_to_add._id == base_vdata._id:
                    current_list.append(vdta_to_add)
                    indicies_added.append(index)
                    listcopy.pop(index)

            grouped_list.append(current_list)
            base_index += 1
            
        series_options = {}
        if not default_series:
            default_series = {}
            default_series[SERIES_LINE_STYLE] = "-"
        series_options_list = __multiple_series_options(default_series, len(unique_locations))
        index = 0
        for location_id in unique_locations:
            series_options[location_id] = series_options_list[index]
            name = location_id
            if project:
                name = project.locations[location_id].name()
            series_options[location_id][SERIES_LABEL] = name
            index += 1
        
        
        for vdata_list in grouped_list:
            #sort proxy list so that all locations have the same style
            vdata_list.sort(key=lambda vd: _loc_id(vd))
            first_vdata = vdata_list[0]
            opts = {}
            opts[PLOT_TITLE] = first_vdata.name()
            opts[PLOT_Y_AXIS_REVERSED] = yaxis_reversed
            #will need to tackle formatting of multiple series here
            options_list = []
            data_list = []
            for vdata in vdata_list:
                options_list.append(series_options[_loc_id(vdata)])
                data_list.append(proxy_xy_values(vdata, project, error_function, yaxis_age))
            opts[PLOT_SERIES_XY_LIST] = data_list
            opts[PLOT_SERIES_OPTIONS_LIST] = options_list
            opts_out.append(opts)
    elif group_by == GROUP_BY_LOCATION:
        grouped_list = []
        listcopy = list(vdata_items)
        base_index = 0
        while True:
            if base_index > len(listcopy)-1:
                break
            base_vdata = listcopy[base_index]
            current_list = []
            current_list.append(base_vdata)
            if base_index == len(listcopy)-1:
                grouped_list.append(current_list)
                break
            indicies_added = []
            for index in reversed(range(base_index+1, len(listcopy))):
                vdta_to_add = listcopy[index]
                if _loc_id(vdta_to_add) == _loc_id(base_vdata):
                    current_list.append(vdta_to_add)
                    indicies_added.append(index)
                    listcopy.pop(index)

            grouped_list.append(current_list)
            base_index += 1
            
        series_options = {}
        if not default_series:
            default_series = {}
            default_series[SERIES_LINE_STYLE] = "-"
        series_options_list = __multiple_series_options(default_series, len(unique_vdata_ids))
        index = 0
        for vdata_id in unique_vdata_ids:
            series_options[vdata_id] = series_options_list[index]
            index += 1
        
        
        for vdata_list in grouped_list:
            first_vdata = vdata_list[0]
            opts = {}
            name = _loc_id(first_vdata)
            if project:
                name = project.locations[_loc_id(first_vdata)].name()
            opts[PLOT_TITLE] = name
            opts[PLOT_Y_AXIS_REVERSED] = yaxis_reversed
            #will need to tackle formatting of multiple series here
            options_list = []
            data_list = []
            for vdata in vdata_list:
                seropts = series_options[vdata._id]
                if not SERIES_LABEL in seropts:
                    seropts[SERIES_LABEL] = vdata.name()
                options_list.append(seropts)
                data_list.append(proxy_xy_values(vdata, project, error_function, yaxis_age))
            opts[PLOT_SERIES_XY_LIST] = data_list
            opts[PLOT_SERIES_OPTIONS_LIST] = options_list
            opts_out.append(opts)
    
    for dendrogram in dendrogram_items:
        series_list = dendrogram_series_list(dendrogram, project, yaxis_age)
        opts = {}
        opts[PLOT_TITLE] = dendrogram.name()
        opts[PLOT_Y_AXIS_REVERSED] = yaxis_reversed
        opts[PLOT_SERIES_XY_LIST] = series_list
        opts[PLOT_SERIES_OPTIONS_LIST] = [{}]*len(series_list)
        opts[PLOT_BORDER_VISIBLE] = False
        opts_out.append(opts)
            
    return opts_out
    
def proxy_xy_values(vdata, project=None, error_function=None, yaxis_age=False):
    depths, values, ns, stdevs, sample_ids = vdata.data_summary()

    if yaxis_age:
        if vdata.key_unit and units.get_category(vdata.key_unit) == "time":
            yvals = depths #because depths are actually time values
        else:
            adm = project.age_depth_model(_loc_id(vdata))
            if adm:
                yvals = [adm.get_age(yval) for yval in depths]
            else:
                raise ValueError("Could not find age depth model for location %s" % _loc_id(vdata))                
    else:
        yvals = depths

    if error_function:
        errors = []
        for index in range(len(values)):
            error = error_function(values[index], ns[index], stdevs[index])
            errors.append(error)
    else:
        errors = stdevs
    
    return [values, yvals, errors]

def dendrogram_series_list(dendrogram, project, yaxis_age=False, x_value_mode=DENDROGRAM_TOTAL_DISSIMILARITY):
    y_value_func = lambda dend: dend.central_key
    if yaxis_age:
        if dendrogram.key_unit and units.get_category(dendrogram.key_unit) == "time":
            y_value_func = lambda dend: dend.central_key
        else:
            adm = project.age_depth_model(_loc_id(dendrogram))
            if adm:
                y_value_func = lambda dend: adm.get_age(dend.central_key)
            else:
                raise ValueError("Could not find age depth model for location %s" % _loc_id(dendrogram))
    
    if x_value_mode == DENDROGRAM_TOTAL_DISSIMILARITY:
        x_value_func = lambda dend: dend.dissimilarity
    elif x_value_mode == DENDROGRAM_INCREASE_DISSIMILARITY:
        x_value_func = lambda dend: dend.dissimilarity_increase
    else:
        raise ValueError("Unrecognized x_value_mode %s" % x_value_mode)
    
    xminmax = __dendrogram_xspread(dendrogram, None, x_value_func)
    sample_tail_length = (xminmax[1] - xminmax[0]) / 10.0
    
    series_list = []
    __dendrogramxy(dendrogram, series_list, y_value_func, x_value_func, sample_tail_length)
    return series_list
    
def __dendrogram_xspread(dendrogram, minmax, x_value_func):
    x = x_value_func(dendrogram)
    if not minmax:
        minmax = [x, x]
    else:
        minmax[0] = min(minmax[0], x)
        minmax[1] = max(minmax[1], x)
        
    if dendrogram.sub_trees is None:
        pass
    else:
        __dendrogram_xspread(dendrogram.sub_trees[0], minmax, x_value_func)
        __dendrogram_xspread(dendrogram.sub_trees[1], minmax, x_value_func)
    return minmax
    

def __dendrogramxy(dendrogram, series_list, y_value_func, x_value_func, sample_tail_length):
    if dendrogram.sub_trees is None:
        pass
    else:
        xvalue = x_value_func(dendrogram)
        d1 = dendrogram.sub_trees[0]
        d2 = dendrogram.sub_trees[1]
        if d1.sub_trees:
            d1x = x_value_func(d1)
        else:
            d1x = xvalue - sample_tail_length
        d1y = y_value_func(d1)
        if d2.sub_trees:
            d2x = x_value_func(d2)
        else:
            d2x = xvalue - sample_tail_length
        d2y = y_value_func(d2)
        
        outx = []
        outy = []
        outx.append(d1x)
        outy.append(d1y)
        
        outx.append(xvalue)
        outy.append(d1y)
        
        outx.append(xvalue)
        outy.append(d2y)
        
        outx.append(d2x)
        outy.append(d2y)
        
        series_list.append([outx, outy])
        __dendrogramxy(d1, series_list, y_value_func, x_value_func, sample_tail_length)
        __dendrogramxy(d2, series_list, y_value_func, x_value_func, sample_tail_length)

def multiplot_export(plot_options_list, file_out, multiplot_options=None, savefig_options=None):
    if savefig_options is None:
        savefig_options = {}
    opts = __merge_options(DEFAULT_MULTIPLOT_OPTIONS, multiplot_options)
    if MULTIPLOT_COLS in opts:
        cols = opts[MULTIPLOT_COLS]
    else:
        cols = len(plot_options_list)
    
    rows = opts[MULTIPLOT_ROWS]
    
    if len(plot_options_list) > rows * cols:
        if file_out.endswith(".pdf") or (("format" in savefig_options) and 
                                                (savefig_options["format"] == "pdf")):
            #process pdf
            
            pages = PdfPages(file_out)
            start_index = 0
            end_index = rows * cols
            
            while True:
                indicies = []
                for index in range(start_index, end_index):
                    if index < len(plot_options_list):
                        indicies.append(index)
                    else:
                        break
                sub_options = [plot_options_list[index] for index in indicies]
                fig = multiplot(sub_options, multiplot_options)
                pages.savefig(fig, **savefig_options)
                if end_index < len(plot_options_list):
                    start_index += rows * cols
                    end_index += rows * cols
                else:
                    break
            pages.close()
        else:
            raise ValueError("Too many figures for the rows and columns specified (multipage pdf output only)")
    else:
        #proess single page output
        fig = multiplot(plot_options_list, multiplot_options)
        fig.savefig(file_out, **savefig_options)


def multiplot(plot_options_list, multiplot_options=None, fig=None):
    opts = __merge_options(DEFAULT_MULTIPLOT_OPTIONS, multiplot_options)
    if MULTIPLOT_COLS in opts:
        cols = opts[MULTIPLOT_COLS]
    else:
        cols = len(plot_options_list)
    
    rows = opts[MULTIPLOT_ROWS]
    
    if MULTIPLOT_Y_AXIS_RANGE in opts:
        y_axis_range = opts[MULTIPLOT_Y_AXIS_RANGE]
        all_tick_labels = False
    elif opts[MULTIPLOT_SYNCHRONIZE_Y_AXIS]:
        miny = None
        maxy = None
        for plotopts in plot_options_list:
            xy_list = plotopts[PLOT_SERIES_XY_LIST]
            for xy_data in xy_list:
                for row in range(len(xy_data[1])):
                    y = xy_data[1][row]
                    if miny is None and not y is None:
                        miny = y
                    elif not y is None and y < miny:
                        miny = y
                        
                    if maxy is None and not y is None:
                        maxy = y    
                    elif not y is None and y > maxy:
                        maxy = y
        if not miny is None and not maxy is None:
            y_axis_range = (miny, maxy)
        else:
            y_axis_range = None
        all_tick_labels = False
    else:
        all_tick_labels = True
        y_axis_range = None
    
    if MULTIPLOT_FIGSIZE in opts:
        figsize = opts[MULTIPLOT_FIGSIZE]
    else:
        figsize = None
    
    if not fig:
        fig = Figure()
    
    if figsize:
        fig.set_size_inches(*figsize)
    
    for subfignum in range(rows*cols):
        if subfignum >= len(plot_options_list):
            break
        opts = plot_options_list[subfignum].copy()
        if y_axis_range:
            opts[PLOT_RANGE_Y_AXIS] = y_axis_range
        if not all_tick_labels:
            if subfignum % cols != 0:
                opts[PLOT_SHOW_Y_AXIS_LABELS] = False
        axes = fig.add_subplot(rows, cols, subfignum+1)
        fig.tight_layout()
        plot(opts, fig, axes)
        
    return fig
        
    

def plot(options, fig=None, axes=None):
    if not PLOT_SERIES_XY_LIST in options:
        raise KeyError("XY data needed to generate plot.")
    
    if not fig:
        fig = Figure()
    if not axes:
        axes = fig.gca()
        
    if PLOT_SERIES_XY_LIST in options:
        data_list = options[PLOT_SERIES_XY_LIST]
        series_options_list = options[PLOT_SERIES_OPTIONS_LIST] if PLOT_SERIES_OPTIONS_LIST in options else None
        
        for index in range(len(data_list)):
            xy_data, xy_error = __series_xy_and_errors(data_list[index])
            series_options = __merge_options(DEFAULT_SERIES_OPTIONS, series_options_list[index]) if series_options_list else DEFAULT_SERIES_OPTIONS
            __add_series(axes, xy_data, xy_error, series_options)
            
    __format_axes(axes, __merge_options(DEFAULT_PLOT_OPTIONS, options))
    
    return fig, axes

def __multiple_series_options(default_series_options, length):
    opts_out = []
    #vary line style
    #['-' | '--' | '-.' | ':' | 'None' | ' ' | '']
    styles = ["-", "--", "-.", ":"]
    markers = ["o", "v", "s", "+", "d", ">", "h", "*", "1", "|", "p", "<"]
    style_index = 0
    marker_index = 0
    for index in range(length):
        opt = {}
        if style_index == len(styles):
            style_index = 0
        opt[SERIES_LINE_STYLE] = styles[style_index]
        style_index += 1
        if marker_index == len(markers):
            marker_index = 0
        opt[SERIES_MARKER] = markers[marker_index]
        marker_index += 1
        opts_out.append(__merge_options(default_series_options, opt))

    return opts_out

def __merge_options(defaults, user_prefs):
    opts_out = defaults.copy()
    if user_prefs:
        for key, value in user_prefs.items():
            opts_out[key] = value
    return opts_out
    
def __format_axes(axes, options):
    if PLOT_TITLE in options:
        val = options[PLOT_TITLE]
        if val:
            axes.set_title(val)
    if PLOT_RANGE_X_AXIS in options:
        val = options[PLOT_RANGE_X_AXIS]
        if val and len(val) == 2:
            axes.set_xlim(val)
    if PLOT_RANGE_Y_AXIS in options:
        val = options[PLOT_RANGE_Y_AXIS]
        if val and len(val) == 2:
            axes.set_ylim(val)
    if PLOT_Y_AXIS_TICKS_COUNT in options:
        val = options[PLOT_Y_AXIS_TICKS_COUNT]
        if val:
            axes.get_yaxis().get_major_locator().set_params(nbins=val)
    if PLOT_X_AXIS_TICKS_COUNT in options:
        val = options[PLOT_X_AXIS_TICKS_COUNT]
        if val:
            axes.get_xaxis().get_major_locator().set_params(nbins=val)
    if PLOT_VALUE_LABEL in options:
        val = options[PLOT_VALUE_LABEL]
        if val:
            axes.set_xlabel(val)
    if PLOT_Y_AXIS_LABEL in options:
        val = options[PLOT_Y_AXIS_LABEL]
        if val:
            axes.set_xlabel(val)
    if PLOT_SHOW_Y_AXIS_LABELS in options:
        if not options[PLOT_SHOW_Y_AXIS_LABELS]:
            axes.get_yaxis().set_ticklabels([])
    if PLOT_SHOW_X_AXIS_LABELS in options:
        if not options[PLOT_SHOW_X_AXIS_LABELS]:
            axes.get_xaxis().set_ticklabels([])
    if PLOT_Y_AXIS_REVERSED in options:
        if options[PLOT_Y_AXIS_REVERSED]:
            axes.invert_yaxis()
    if PLOT_X_AXIS_VISIBLE in options:
        axes.get_xaxis().set_visible(options[PLOT_X_AXIS_VISIBLE])
    if PLOT_Y_AXIS_VISIBLE in options:
        axes.get_yaxis().set_visible(options[PLOT_Y_AXIS_VISIBLE])
    if PLOT_BORDER_VISIBLE in options:
        val = options[PLOT_BORDER_VISIBLE]
        if not val:
            axes.spines['top'].set_visible(False)
            axes.spines['right'].set_visible(False)
            axes.spines['bottom'].set_visible(False)
            axes.spines['left'].set_visible(False)
    if PLOT_BACKGROUND in options:
        axes.patch.set_visible(options[PLOT_BACKGROUND])

def __add_series(axes, xy_data, xy_error, options):
    plotopts = options.copy()
    if SERIES_ERROR_BARS in plotopts:
        if plotopts[SERIES_ERROR_BARS] and xy_error:
            #plot error data
            axes.errorbar(xy_error[0], xy_error[1], xy_error[3], xy_error[2], color="#000000", visible=False)
        #delete this key, not used in axes.plot()
        del plotopts[SERIES_ERROR_BARS]   
    axes.plot(xy_data[0], xy_data[1], **plotopts)
    
def __series_xy_and_errors(in_array):
    cols = len(in_array)
    xs = []
    ys = []

    err_y = []
    err_x = []
    err_errx = []
    err_erry = []
    
    for row_index in range(len(in_array[0])):
        x = in_array[0][row_index]
        y = in_array[1][row_index]
        
        if cols >= 3:
            xerr = in_array[2][row_index]
        else:
            xerr = 0
        
        if cols >= 4:
            yerr = in_array[3][row_index]
        else:
            yerr = 0
        
        xs.append(x)
        ys.append(y)
        
        if xerr or yerr:
            err_x.append(x)
            err_y.append(y)
            err_errx.append(xerr)
            err_erry.append(yerr)

    return [xs, ys], [err_x, err_y, err_errx, err_erry]
    
    
    
    
    
    
#     THIS TEST NOT UPDATED TO NEW MODEL
# if __name__ == "__main__":
#     #test of plot()
#     from proxy_model.proxydata import *
#     from proxy_model.proxyfiles import *
#     from proxy_model.dataprocessing import least_squares_cluster, create_dendrogram, data_table_averaged
#     import matplotlib.pyplot as plt
#     
#     data1 = [[0.1, 0.2, 0.3, 0.1, 0.2, 0.3, 0.4, 0.1, 0.2, 0.3],
#              [1,2,3,4,5,6,7,8,9,10], 
#              [None, None, .05, None, None, .05, None, None, .05, None]]
#     
#     data2 = [[0.1, 0.2, 0.3, 0.1, 0.2, 0.3, 0.4, 0.1, 0.2, 0.3],
#              [2,4,6,8,10,11,12,13,14,17], 
#              [None, None, .06, None, None, .06, None, None, .06, None]]
#     
#     proxy1 = ProxyData("proxy1")
#     for row in range(10):
#         proxy1.add_value(data1[1][row], data1[0][row], None)
#     proxy2 = ProxyData("proxy2")
#     for row in range(10):
#         proxy2.add_value(data2[1][row], data2[0][row], None)
#     
#     proxy3 = ProxyData("proxy1")
#     for row in range(10):
#         proxy3.add_value(data1[1][row]*3, data1[0][row], None)
#     
#     loc1 = ProxyLocation("location1")
#     loc1.add_proxy(proxy1)
#     loc1.add_proxy(proxy2)
#     
#     loc2 = ProxyLocation("location2")
#     loc2.add_proxy(proxy3)
#     
#     project = ProxyProject()
#     project.add_location(loc1)
#     project.add_location(loc2)
#     
#     clusterdata = [[0.1, 0.2, 0.3, 0.1, 0.2, 0.3, 0.4, 0.1, 0.2, 0.3], [0.8, 2.2, 5.3, 1.1, 0.8, 8.6, 2.5, 0.2, 0.1, 2.2]]
#     clusterdepths = [1,2,3,4,5,6,7,8,9,10]
#     rootcluster = least_squares_cluster(np.array(clusterdata).T, True)
#     dendrogram = create_dendrogram(rootcluster, clusterdepths, None)
#     print(dendrogram)    
#     proxy_list = [proxy1, proxy3, proxy2, dendrogram]
#     
#     pl = data_table_averaged([proxy1, proxy3, proxy2], True)
#     print(pl)
#     
#     options = generate_plot_options(proxy_list, project=project, group_by=GROUP_BY_PROXY)
#     
#     multi_opts = {}
#     multi_opts[MULTIPLOT_COLS] = 4
#     multi_opts[MULTIPLOT_FIGSIZE] = (11, 8.5)
#     multiplot_export(options, "/Users/dewey/Desktop/test.pdf", multiplot_options=multi_opts)
#     
#     
    
    
    
    
    
